/**
 * 
 */
package sqlengine.groupby;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;

import sqlengine.parser.ParseException;

/**
 * @author ibm
 *
 */
public class TableDef extends Atom {
	private String tableName;
	
	Map<String, Integer> descriptor = new HashMap<String, Integer>();
	Vector<String> order = new Vector<String>();

	public Vector<String> getOrder() {
		return order;
	}

	public void setOrder(Vector<String> order) {
		this.order = order;
	}



	private String key = null;
	private boolean lock = false;
	/**
	 * Default constructor
	 * 
	 * @param tableStr
	 *            the name of the table referenced by this
	 *            <code>TableDef</code>
	 */
	public TableDef(){}
	
	public TableDef(String tableStr) {
		tableName = tableStr;		
	}
	/**
	 * Gets the name of the table referenced by this <code>TableDef</code> 
	 * @return the table name
	 */
	public String getTableName() {
		return tableName;
	}

	public String getKey() {
		return key;
	}
	
	public 	Map<String, Integer> getDescriptor() {
		return Collections.unmodifiableMap(descriptor);
	}
	
	public void setTableName(String tablename){
		tableName = tablename;
	}
	
	public void setKey(String k) {		
		if(lock){
			throw new IllegalArgumentException();
		}
		key = k;
		lock = true;
	}
	
	public void addDescriptor(String colname, int length) throws ParseException {
		if(descriptor.containsKey(colname)){
			System.err.println("Duplicate column name "+"\'" + colname + "\'");
			throw new IllegalArgumentException();
		}
		descriptor.put(colname, length);
		order.add(colname);
	} 	
	

	/**
	 * @see edu.buffalo.db.parser.sqlexpr.Atom#getType()
	 */
	@Override
	public int getType() {
		return Atom.TABLE_DEF_ATOM;
	}

	/**
	 * @see java.lang.Object#hashCode()
	 */
	@Override
	public int hashCode() {
		final int PRIME = 31;
		int result = 1;
		result = PRIME * result + ((key == null) ? 0 : key.hashCode());
		result = PRIME * result
				+ ((tableName == null) ? 0 : tableName.hashCode());
		return result;
	}


	
	/**
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String str = "Table: "+tableName +"\n";		
		if (key != null)
			str += "Key: " + key + "\n";
		
		Iterator it = descriptor.entrySet().iterator();		
		while (it.hasNext()) {
			Map.Entry pairs = (Map.Entry) it.next();
			str += pairs.getKey() + " " + pairs.getValue() + "\n";
		}
		return str;
	}
}
